require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const { sequelize } = require('./models');
const debugRoutes = require('./routes/debug');
const userRoute = require('./routes/users');

const app = express();
app.use(bodyParser.json());

// 用户路由
app.use('/api/users', userRoute);

// 修复健康检查路由
app.get('/health', (req, res) => {
  res.json({ 
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    remark: '健康检查成功，数据服务正常 - Sequelize版本',
    version: require('./package.json').version,
    author: require('./package.json').author
  });
});

// 注册路由 - 使用 /api 前缀
app.use('/api', debugRoutes);

const PORT = process.env.PORT || 3304;

async function startServer() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');

    if (process.env.DB_SYNC === 'true') {
      await sequelize.sync({ alter: true });
      console.log('数据库模型同步完成 (DB_SYNC=true)');
    } else {
      console.log('跳过自动同步（DB_SYNC !== "true"）');
    }

    app.listen(PORT, () => {
      console.log(`服务器运行在端口 ${PORT}`);
      console.log(`健康检查地址：http://localhost:${PORT}/health`);
      console.log(`用户接口地址：http://localhost:${PORT}/api/users`);
      console.log(`调试接口地址：http://localhost:${PORT}/api/debug/users`);
    });
  } catch (err) {
    console.error('启动失败：', err);
    process.exit(1);
  }
}

startServer();
module.exports = app;